package com.example.video

import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.base.mvvm.BaseActivity
import com.example.video.adapter.OneAdapter
import com.example.video.adapter.TwoAdapter
import com.example.video.databinding.ActivityCateBinding

class CateActivity : BaseActivity<ActivityCateBinding,CategoryViewModel>() {
    //初始化rv
    lateinit var oneAdapter: OneAdapter
    lateinit var twoAdapter: TwoAdapter
    var flag = false//标记是否是自动滚动（非人为滑动）
    override fun initView() {
        oneAdapter = OneAdapter()
        binding.rvOne.adapter = oneAdapter
        binding.rvOne.layoutManager = LinearLayoutManager(this)

        twoAdapter = TwoAdapter()
        val linearLayoutManager = LinearLayoutManager(this)
        binding.rvTwo.layoutManager  = linearLayoutManager
        binding.rvTwo.adapter = twoAdapter

        viewModel.category()

        //点击一级分类item，二级分类滚动
        oneAdapter.setOnItemClickListener { adapter, view, position ->
            //文字颜色发送变化
            oneAdapter.setType(oneAdapter.data[position].id)
            //修改flag状态  改成自动的
            flag = true
            linearLayoutManager.scrollToPositionWithOffset(position,0)
            //滚动完成，状态恢复成不自动滚动
            flag = false
        }
        //滚动二级分类，对应一级分类发生变化
        binding.rvTwo.addOnScrollListener(object :RecyclerView.OnScrollListener(){
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if(!flag){//非自动滚动状态
                    val position =
                        linearLayoutManager.findFirstVisibleItemPosition()
                    //当显示的二级分类下标和一级分类选中的下标不一致，进行更新
                    if(twoAdapter.data[position].id!=oneAdapter.selectType){
                        oneAdapter.setType(twoAdapter.data[position].id)
                    }

                }
            }
        })
    }

    override fun initData() {
        viewModel.cateSuccess.observe(this){
            if(it.code==200){
                oneAdapter.data.clear()
                oneAdapter.data.addAll(it.data)
                oneAdapter.notifyDataSetChanged()

                twoAdapter.data.clear()
                twoAdapter.data.addAll(it.data)
                twoAdapter.notifyDataSetChanged()
            }
        }
    }

    override fun getViewModel(): Class<CategoryViewModel> {
        return CategoryViewModel::class.java
    }

    override fun getLayout(): Int {
        return  R.layout.activity_cate
    }

}